package com.swak.nio_udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

/**
 * 特点： 1. 加入组 2. 主动的获取获取（阻塞式）
 * 
 * @author lifeng
 */
public class MuiltcastDemo {

	private static int PORT = 5555;
	private static String MULTICAST_ADDRESS = "225.0.0.2";

	static class MulticastClient {

		/**
		 * MulticastSocket 继承至   DatagramSocket
		 */
		private MulticastSocket socket;
		private String id;
		private InetAddress group;
		private int port;

		@SuppressWarnings("deprecation")
		public MulticastClient(final String id, InetAddress group, int port) throws IOException {
			this.id = id;
			this.group = group;
			this.port = port;
			socket = new MulticastSocket(port);
			socket.joinGroup(group);
			final byte[] buf = new byte[256];
			new Thread(new Runnable() {
				@Override
				public void run() {
					while (true) {
						try {
							DatagramPacket packet = new DatagramPacket(buf, buf.length);
							// 阻塞直到数据准备好
							socket.receive(packet);
							String msg = new String(packet.getData());
							System.out.println("客户端" + id + "接受到的数据：" + msg);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();

		}

		@SuppressWarnings("deprecation")
		public void send(String msg) {
			byte[] bytes = msg.getBytes();
			try {
				socket.leaveGroup(group);// 发送的人不接收组播消息
				msg = "客户端" + id + "发送数据：" + msg;
				System.out.println(msg);
				socket.send(new DatagramPacket(bytes, bytes.length, group, port));
				socket.joinGroup(group);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		MulticastClient mcA = new MulticastClient("A", InetAddress.getByName(MULTICAST_ADDRESS), PORT);
		MulticastClient mcB = new MulticastClient("B", InetAddress.getByName(MULTICAST_ADDRESS), PORT);
		MulticastClient mcC = new MulticastClient("C", InetAddress.getByName(MULTICAST_ADDRESS), PORT);

		mcA.send("Hello!");
		TimeUnit.SECONDS.sleep(2);
		mcB.send("Hello!");
		TimeUnit.SECONDS.sleep(2);
		mcC.send("Hello!");
		TimeUnit.SECONDS.sleep(2);
		
		TimeUnit.SECONDS.sleep(100000);
	}

}
